package com.taxi.driver.module.main.mine.wallet.withdrawal;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.qianxx.view.HeadView;
import com.taxi.driver.BuildConfig;
import com.taxi.driver.R;
import com.taxi.driver.common.Application;
import com.taxi.driver.common.BaseActivity;
import com.taxi.driver.module.main.mine.wallet.withdrawal.dagger.DaggerWithdrawalComponent;
import com.taxi.driver.module.main.mine.wallet.withdrawal.dagger.WithdrawalModule;
import com.taxi.driver.module.vo.WithdrawalVO;
import com.taxi.driver.util.Navigate;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;

/**
 * 提现
 */
public class WithdrawalActivity extends BaseActivity implements WithdrawalContract.View {

    @BindView(R.id.head_view)
    HeadView mHeadView;
    @BindView(R.id.tv_withdrawal_to_the_card)
    TextView mTvWithdrawalToTheCard;
    @BindView(R.id.tv_withdrawal_to_the_weixin)
    TextView mTvWithdrawalToTheWeixin;
    @BindView(R.id.tv_withdrawal_to_the_zhifubao)
    TextView mTvWithdrawalToTheZhifubao;
    @BindView(R.id.iv_hook1)
    ImageView mIvHook1;
    @BindView(R.id.iv_hook2)
    ImageView mIvHook2;
    @BindView(R.id.iv_hook3)
    ImageView mIvHook3;
    @BindView(R.id.tv_can_be_withdrawal_amount)
    TextView mTvCanBeWithdrawalAmount;
    @BindView(R.id.tv_the_actual_to_account)
    TextView mTvTheActualToAccount;
    @BindView(R.id.tv_account_name)
    TextView mTvAccountName;
    @BindView(R.id.btn_withdrawal)
    Button mBtnWithdrawal;
    @BindView(R.id.et_withdrawal_account)
    EditText mEtWithdrawalAccount;
    @BindView(R.id.et_withdrawal_money)
    EditText mEtWithdrawalMoney;
    @BindView(R.id.et_login_password)
    EditText mEtLoginPassword;

    private final static int WITHDRAWAL_TO_CARD = 1;
    private final static int WITHDRAWAL_TO_WEIXIN = 2;
    private final static int WITHDRAWAL_TO_ZHIFUBAO = 3;

    // 提现方式
    private int collectType = WITHDRAWAL_TO_CARD;

    private WithdrawalVO vo;
    // 小数点位数
    private final static int DECIMAL_DIGITS = 1;

    @Inject
    WithdrawalPresenter mPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 该属性能防止屏幕被截图和录制。这个属性就是可以防止当前Activity不会被录制
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
        setContentView(R.layout.activity_withdrawal);
        ButterKnife.bind(this);

        DaggerWithdrawalComponent.builder()
                .appComponent(Application.getAppComponent())
                .withdrawalModule(new WithdrawalModule(this))
                .build()
                .inject(this);

        // 初始显示"本次可提现金额为0元"
        mTvCanBeWithdrawalAmount.setText(getString(R.string.can_be_withdrawal_amount, "0.0"));
        // 初始显示"实际到账0.0元"
            mTvTheActualToAccount.setText(getString(R.string.the_actual_to_account, "0.0"));

        // 请求司机信息
        mPresenter.reqDriverInfo();
    }

    @OnClick({R.id.rl_withdrawal_to_the_card, R.id.rl_withdrawal_to_the_weixin,
            R.id.rl_withdrawal_to_the_zhifubao, R.id.rl_account_name, R.id.btn_withdrawal})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_withdrawal_to_the_card://提现到银行卡
                collectType = WITHDRAWAL_TO_CARD;

                //实际可提现金额
                double actual;
                //手续费
                double poundage;
                //提现金额
                double withdrawalMoney = Double.parseDouble(TextUtils.isEmpty(mEtWithdrawalMoney.getText().toString()) ?
                        "0.0" : mEtWithdrawalMoney.getText().toString());
                if (vo.poundageType == 1) {
                    poundage = vo.poundageMoney;
                } else {
                    poundage = withdrawalMoney * vo.percent / 100.0;
                }

                actual = withdrawalMoney - poundage;
                if (actual < 0) {
                    actual = 0.0;
                }
                mTvTheActualToAccount.setText(getString(R.string.the_actual_to_account, actual + ""));

                mTvWithdrawalToTheCard.setTextColor(getResources().getColor(R.color.text_4f5a67));
                mTvWithdrawalToTheWeixin.setTextColor(getResources().getColor(R.color.text_9ea7b1));
                mTvWithdrawalToTheZhifubao.setTextColor(getResources().getColor(R.color.text_9ea7b1));
                mIvHook1.setVisibility(View.VISIBLE);
                mIvHook2.setVisibility(View.GONE);
                mIvHook3.setVisibility(View.GONE);
                break;
            case R.id.rl_withdrawal_to_the_weixin://提现到微信
                collectType = WITHDRAWAL_TO_WEIXIN;

                //实际可提现金额
                String actual2 = TextUtils.isEmpty(mEtWithdrawalMoney.getText().toString()) ? "0.0" : mEtWithdrawalMoney.getText().toString();
                mTvTheActualToAccount.setText(getString(R.string.the_actual_to_account, actual2));

                mTvWithdrawalToTheCard.setTextColor(getResources().getColor(R.color.text_9ea7b1));
                mTvWithdrawalToTheWeixin.setTextColor(getResources().getColor(R.color.text_4f5a67));
                mTvWithdrawalToTheZhifubao.setTextColor(getResources().getColor(R.color.text_9ea7b1));
                mIvHook1.setVisibility(View.GONE);
                mIvHook2.setVisibility(View.VISIBLE);
                mIvHook3.setVisibility(View.GONE);
                break;
            case R.id.rl_withdrawal_to_the_zhifubao://提现到支付宝
                collectType = WITHDRAWAL_TO_ZHIFUBAO;

                //实际可提现金额
                String actual3 = TextUtils.isEmpty(mEtWithdrawalMoney.getText().toString()) ? "0.0" : mEtWithdrawalMoney.getText().toString();
                mTvTheActualToAccount.setText(getString(R.string.the_actual_to_account, actual3));

                mTvWithdrawalToTheCard.setTextColor(getResources().getColor(R.color.text_9ea7b1));
                mTvWithdrawalToTheWeixin.setTextColor(getResources().getColor(R.color.text_9ea7b1));
                mTvWithdrawalToTheZhifubao.setTextColor(getResources().getColor(R.color.text_4f5a67));
                mIvHook1.setVisibility(View.GONE);
                mIvHook2.setVisibility(View.GONE);
                mIvHook3.setVisibility(View.VISIBLE);
                break;
            case R.id.rl_account_name:
                toast(getResources().getString(R.string.can_not_change));
                break;
            case R.id.btn_withdrawal:
                withdrawal();
                break;
        }
    }

    /**
     * 提现
     */
    public void withdrawal() {
        // 提现账号
        String collectAccount = mEtWithdrawalAccount.getText().toString();
        // 提现账号不能为空
        if (TextUtils.isEmpty(collectAccount)) {
            toast(getResources().getString(R.string.please_input_withdrawal_account));
            return;
        }
        // 如果提现方式是"提现到银行卡"，检查提现账号的格式
        if (collectType == WITHDRAWAL_TO_CARD && !checkAccount(collectAccount)) {
            toast(getResources().getString(R.string.invalid_format));
            return;
        }

        // 提现金额不能为空
        if (TextUtils.isEmpty(mEtWithdrawalMoney.getText().toString())) {
            toast(getResources().getString(R.string.please_input_money));
            return;
        }
        // 提现金额
        double withdrawalMoney = Double.parseDouble(mEtWithdrawalMoney.getText().toString());
        // 提现金额不能小于等于0
        if (withdrawalMoney <= 0) {
            toast(getResources().getString(R.string.withdrawal_amount_more_than_zero));
            return;
        }
        // 提现金额不可以打于账号余额(最大可提现金额)
        if (withdrawalMoney > vo.balance) {
            toast(getResources().getString(R.string.withdrawal_amount_exceeds_the_limit));
            return;
        }

        // 手续费
        double poundage;
        // 如果提现方式是微信|支付宝,手续费为0
        if (collectType == WITHDRAWAL_TO_WEIXIN || collectType == WITHDRAWAL_TO_ZHIFUBAO) {
            poundage = 0.0;
        } else {
            // 判断手续费类型
            if (vo.poundageType == 1) {
                poundage = vo.poundageMoney;
            } else {
                poundage = withdrawalMoney * vo.percent / 100.0;
            }
        }
        // 提现金额不足于扣除手续费
        if (withdrawalMoney < poundage) {
            toast(getResources().getString(R.string.withdrawal_amount_is_not_enough_to_pay_the_fees));
            return;
        }

        // 账号密码
        String password = mEtLoginPassword.getText().toString();
        // 账号密码不能为空
        if (TextUtils.isEmpty(password)) {
            toast(getResources().getString(R.string.for_security_please_enter_the_password));
            return;
        }

        //提现
        mPresenter.withdrawal(withdrawalMoney + "", collectAccount, collectType, password);
    }

    /**
     * 检查账户是否是纯数字,并且数字在16或者19位
     *
     * @param collectAccount
     * @return
     */
    public boolean checkAccount(String collectAccount) {
        Pattern p = Pattern.compile("^(\\d{16}|\\d{19})$");
        Matcher m = p.matcher(collectAccount);
        return m.matches();
    }

    @OnTextChanged({R.id.et_withdrawal_money})
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        //限制只能取1位小数点
        if (!TextUtils.isEmpty(s.toString())) {
            if (s.toString().contains(".")) {
                if (s.length() - 1 - s.toString().indexOf(".") > DECIMAL_DIGITS) {
                    s = s.toString().subSequence(0,
                            s.toString().indexOf(".") + DECIMAL_DIGITS + 1);
                    mEtWithdrawalMoney.setText(s);
                    mEtWithdrawalMoney.setSelection(s.length());
                }
            }
            if (s.toString().trim().equals(".")) {
                s = "0" + s;
                mEtWithdrawalMoney.setText(s);
                mEtWithdrawalMoney.setSelection(2);
            }
            if (s.toString().startsWith("0")
                    && s.toString().trim().length() > 1) {
                if (!s.toString().substring(1, 2).equals(".")) {
                    mEtWithdrawalMoney.setText(s.subSequence(0, 1));
                    mEtWithdrawalMoney.setSelection(1);
                    return;
                }
            }
        }

        // 计算并显示实际到账
        double actual;
        double poundage;
        // 如果提现方式是微信|支付宝,手续费为0
        if (collectType == WITHDRAWAL_TO_WEIXIN || collectType == WITHDRAWAL_TO_ZHIFUBAO) {
            poundage = 0.0;
        } else {
            if (vo.poundageType == 1) {
                poundage = vo.poundageMoney;
            } else {
                poundage = Double.parseDouble(TextUtils.isEmpty(s.toString()) ? "0" : s.toString()) * vo.percent / 100.0;
            }
        }
        actual = Double.parseDouble(TextUtils.isEmpty(s.toString()) ? "0" : s.toString()) - poundage;
        if (actual < 0) {
            actual = 0.0;
        }
        // 显示实际到账金额
        mTvTheActualToAccount.setText(getString(R.string.the_actual_to_account, actual + ""));
    }

    @Override
    public int getBarColor() {
        return R.color.theme_color;
    }

    @Override
    public boolean isActive() {
        return false;
    }

    /**
     * 显示司机信息
     *
     * @param vo
     */
    @Override
    public void showDriverInfo(WithdrawalVO vo) {
        this.vo = vo;
        // 显示司机名称
        mTvAccountName.setText(vo.driverName);
        // 显示本次可提现最大金额
        mTvCanBeWithdrawalAmount.setText(getString(R.string.can_be_withdrawal_amount, String.format("%.01f", vo.balance)));
        if (vo.poundageType == 1) {
            // 显示手续费

                mTvWithdrawalToTheCard.setText(getString(R.string.withdrawal_to_the_card2, vo.poundageMoney + "元"));


        } else {
            // 显示手续费比例

                mTvWithdrawalToTheCard.setText(getString(R.string.withdrawal_to_the_card2, vo.percent + "%"));

        }
    }

    /**
     * 提现成功
     */
    @Override
    public void withdrawalSucc() {
        toast(getResources().getString(R.string.withdrawal_success));
        Navigate.openWithdrawalRecord(this);
        finish();
    }

    /**
     * 提现失败
     *
     * @param errCode 错误码
     * @param errMsg  错误原因
     */
    @Override
    public void withdrawalFail(int errCode, String errMsg) {
        toast(errMsg);
    }
}
